package cn.tedu.d21_socket.demo;

import java.io.*;
import java.net.Socket;
import java.util.Scanner;

public class Client {
    Socket socket;

    public Client(String host,int port){
        try {
            System.out.println("连接服务器...");
            socket=new Socket(host,port);
            System.out.println("连接服务器成功!");
        } catch (Exception e) {
            //打印错误堆栈
            e.printStackTrace();
            System.out.println("连接服务器失败！");
        }
    }

    //业务方法
    public void start(){
        try {
            OutputStream os =
                    socket.getOutputStream();
            BufferedOutputStream bos
                    =new BufferedOutputStream(os);
            OutputStreamWriter osw
                    =new OutputStreamWriter(bos,"utf-8");
            PrintWriter pw=new PrintWriter(osw,true);
            Scanner s=new Scanner(System.in);

            //输入流
            InputStream in= socket.getInputStream();
            BufferedInputStream bis=new BufferedInputStream(in);
            InputStreamReader isr=new InputStreamReader(bis,"utf-8");
            BufferedReader br=new BufferedReader(isr);

            String line=null;
            String line2=null;
            while (true) {
                System.out.println("请输入内容；");
                line=s.nextLine();
                if(line.equalsIgnoreCase("EXIT")) break;
                pw.println(line);

                line2=br.readLine();
                System.out.println(line2);
            }
            pw.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        //172.199.11.43
        Client c=new Client("172.199.11.43",8080);
        c.start();
    }
}
